# app/services/upload_service.py

from flask import current_app, g

from app.services.doubao.ElseBasedUBALDO import ElseBasedUBALDO
from app.services.doubao.model_dispatcher import ModelDispatcher
from app.services.file_service import allowed_file, save_uploaded_file
from app.services.ocr.service.async_service import async_save_record
from app.services.ocr.service.question_matcher import QuestionMatcher
from app.services.ocr.utils.ocr_engine import recognize_image
from app.services.user_service import validate_user
from concurrent.futures import ThreadPoolExecutor

# 创建线程池
executor = ThreadPoolExecutor(max_workers=5)


class UploadService:
    def match_question(self, ocr_text, file_path):
        match_result = QuestionMatcher.match(ocr_text, file_path)
        return match_result

    def handle_upload(self, user_id, file, device_info, ip_address):

        user, error = validate_user(user_id)
        if not user:
            return {"code": 0, "msg": error}

        if not file or not allowed_file(file.filename):
            return {"code": 0, "msg": "文件无效或类型不支持"}

        file_content = file.read()
        file.stream.seek(0)  # 必须重置！
        filepath = save_uploaded_file(file)
        ocr_result = recognize_image(filepath)
        print("识别到的内容",ocr_result)
        if not ocr_result:
            return {"code": 1, "error": "未识别到文字"}

        ocr_text = ocr_result.get("raw_text", "")
        match_result = self.match_question(ocr_text, filepath)
        is_success = bool(match_result)
        recognition_result = 'success' if is_success else 'failed'
        success_rate = min(98.0, max(60.0, match_result[0].get('similarity', 0.5) * 100)) if is_success else 0.0

        # 获取当前应用上下文
        app = current_app._get_current_object()  # 获取真实应用对象而非代理

        # 提交任务时包装上下文
        def task_with_context(*args, **kwargs):
            with app.app_context():
                return async_save_record(*args, **kwargs)

        executor.submit(task_with_context, file_content, ocr_text, match_result, user, device_info,
                        ip_address, recognition_result, success_rate, g.tenant_id)
        return {
            "code": 1,
            "results": match_result,
            "count": len(match_result),
            "keyword": ocr_text
        }

    def handle_upload_ai(self, user_id, file, device_info, ip_address):
        user, error = validate_user(user_id)
        if not user:
            return {"code": 0, "msg": error}
        if not file or not allowed_file(file.filename):
            return {"code": 0, "msg": "文件无效或类型不支持"}
        file.stream.seek(0)  # 必须重置！
        filepath = save_uploaded_file(file)

        engine = ModelDispatcher.get_model('else_image')
        ocr_result = engine.recognize(filepath, None)
        return {
            "code": 1,
            "ai_result": ocr_result,
        }
